#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ======================================#
# @Author   : duanqizhong
# @time     : 2020/6/25 17:07
# @file     : redis_table.py
# @Software : PyCharm
# ======================================#

from apps.client.redis_client import Redis
from apps.settings import REDIS_CACHE_TABLES


def redis_table_all_cache(func):
    """如果查询表的条件为空，缓存整张表数据"""

    def _cache_table(*args, **kwargs):
        table = args[0]
        if table is not None and table in REDIS_CACHE_TABLES and not args[1]:
            table_info = Redis.get_json(f"table_{table}")
            if table_info is None or not table_info:
                table_info = func(*args, **kwargs)
                if table_info["data"]:
                    Redis.set_json(f"table_{table}", table_info)
        else:
            """where is exists"""
            table_info = func(*args, **kwargs)
        return table_info

    return _cache_table


def redis_delete_cache(func):
    """如果更新表，更新前删除一次，更新后删除一次redis"""

    def _del_cache(*args, **kwargs):
        table = args[0]
        # 更新前删除
        Redis.delete(f"table_{table}")
        table_info = func(*args, **kwargs)
        # 更新后删除，确保一致性
        Redis.delete(f"table_{table}")
        return table_info

    return _del_cache
